package main

import (
	"gitee.com/w5681688/cart/domian/repository"
	service2 "gitee.com/w5681688/cart/domian/service"
	"gitee.com/w5681688/cart/handler"
	"gitee.com/w5681688/cart/proto/cart"
	"gitee.com/w5681688/common"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/micro/go-micro/v2"
	"github.com/micro/go-micro/v2/registry"
	"github.com/micro/go-plugins/registry/consul/v2"
	ratelimit "github.com/micro/go-plugins/wrapper/ratelimiter/uber/v2"
	opentracing2 "github.com/micro/go-plugins/wrapper/trace/opentracing/v2"
	"github.com/opentracing/opentracing-go"
	"log"
)

var QPS = 100

func main() {
	//配置中心om

	consulConfig, err := common.GetConsulConfig("127.0.0.1", 8500, "micro/config")
	if err != nil {
		log.Fatal(err)
	}
	//注册中心
	consulRegister := consul.NewRegistry(func(options *registry.Options) {
		options.Addrs = []string{
			"127.0.0.1:8500",
		}
	})
	t, io, err := common.NewTracer("go.micro.service.cart", "localhost:6832")
	if err != nil {
		log.Fatal(err)
	}
	defer io.Close()
	opentracing.SetGlobalTracer(t)

	//数据库连接
	mysqlInfo := common.GetMysqlFromConsul(consulConfig, "mysql")

	// 连接数据库
	db, err := gorm.Open("mysql", mysqlInfo.User+":"+mysqlInfo.Password+"@tcp"+"("+mysqlInfo.Host+")/"+mysqlInfo.Database+"?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	//禁止副表
	db.SingularTable(true)
	//初始化表
	err = repository.NewCartRepository(db).InitTable()
	if err != nil {
		log.Fatal(err)
	}
	// Create service
	srv := micro.NewService(
		micro.Name("go.micro.service.cart"),
		micro.Version("latest"),
		//暴露的服务地址
		micro.Address("0.0.0.0:8087"),
		//注册中心
		micro.Registry(consulRegister),
		//链路追踪
		micro.WrapHandler(opentracing2.NewHandlerWrapper(opentracing.GlobalTracer())),
		//添加限流
		micro.WrapHandler(ratelimit.NewHandlerWrapper(QPS)),
	)
	srv.Init()
	// Run service
	cartservice := service2.NewCartService(repository.NewCartRepository(db))
	cart.RegisterCartHandler(srv.Server(), &handler.Cart{cartservice})

	if err := srv.Run(); err != nil {
		log.Fatal(err)
	}
}
